package config

import (
	"fmt"
	"strings"

	"playbook/ginsvr/src/global"
	"playbook/ginsvr/src/orm"

	"github.com/go-ini/ini"
)

type VersionConfig struct {
	FrontEnd string `ini:"frontend"`
	BackEnd  string `ini:"backend"`
}

type AuditFieldConfig struct {
	Startfield string `ini:"startfield"`
	Starttype  string `ini:"starttype"`
	Endfield   string `ini:"endfield"`
	Endtype    string `ini:"endtype"`
}

type TypeOptional struct {
	Value string `ini:"value"`
	Label string `ini:"label"`
}

type Config struct {
	VersionConfig    VersionConfig    `ini:"version"`
	AuditFieldConfig AuditFieldConfig `ini:"auditfiled"`
	JavaTypeConfig   TypeOptional     `ini:"javatype"`
	Mappingtype      TypeOptional     `ini:"mappingtype"`
}

func GetVersionConfig() VersionConfig {
	var cfg = new(Config)
	err := ini.MapTo(cfg, "config.ini")
	if err != nil {
		fmt.Print(err)
	}
	return cfg.VersionConfig
}

func getAuditFieldConfig(auditfield AuditFieldConfig) map[string]interface{} {
	startfield := auditfield.Startfield
	starttype := auditfield.Starttype
	endfield := auditfield.Endfield
	endtype := auditfield.Endtype
	configmap := make(map[string]interface{})
	configmap["inputFixedParams"] = getparams(startfield, starttype)
	configmap["outputFixedParams"] = getparams(endfield, endtype)
	return configmap
}

func getparams(fieldstr string, typestr string) []map[string]interface{} {
	fields := strings.Split(fieldstr, ",")
	types := strings.Split(typestr, ",")
	var paramlist []map[string]interface{}
	for i, str := range fields {
		parammap := make(map[string]interface{})
		parammap["name"] = str
		parammap["mappingname"] = str
		parammap["type"] = types[i]
		parammap["optional"] = "false"
		parammap["classPath"] = types[i]
		paramlist = append(paramlist, parammap)
	}
	return paramlist
}

func getTypeOptions(valuestr string, typestr string) []map[string]interface{} {
	values := strings.Split(valuestr, ",")
	types := strings.Split(typestr, ",")
	var optionalist []map[string]interface{}
	for i, str := range values {
		optionalmap := make(map[string]interface{})
		optionalmap["value"] = str
		optionalmap["label"] = types[i]
		optionalist = append(optionalist, optionalmap)
	}
	return optionalist
}

func GetConfig(configtype string) interface{} {
	var cfg = new(Config)
	err := ini.MapTo(cfg, "config.ini")
	if err != nil {
		global.LOG.Infof("查询配置信息失败，%d\n", err)
		return orm.Response{
			RespCode: "000001",
			RespMsg:  "查询配置信息失败",
		}
	}
	switch configtype {
	case "version":
		return cfg.VersionConfig
	case "auditfiled":
		return getAuditFieldConfig(cfg.AuditFieldConfig)
	case "javatype":
		return getTypeOptions(cfg.JavaTypeConfig.Value, cfg.JavaTypeConfig.Label)
	case "mappingtype":
		return getTypeOptions(cfg.Mappingtype.Value, cfg.Mappingtype.Label)
	default:
		return orm.Response{
			RespCode: "000002",
			RespMsg:  "查询配置类型错误",
		}
	}
}
